/******************************************************************************\
    Error.cpp contains a function that shows a message box with error 
	 discription.
    It's used with acm server. See main.cpp for details.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#include <windows.h>
#include ".\Error.h"
#include <string>
#include ".\Common.h"
#include <vector>
#include <Common\String.h>
using namespace std;

static vector< string > Error( 1, "No error" );

int NewErrorV( const char format[], va_list arg_list )
{
	int result = ( int )Error.size();
	Error.push_back( StringPrintfV( format, arg_list ) );
	return result;
}

int NewError( const char format[], ... )
{
	va_list arg_list;
	va_start( arg_list, format );
	int result = NewErrorV( format, arg_list );
	va_end( arg_list );
	return result;
}

std::string GetError( unsigned long index )
{
	if( index < 0 || Error.size() <= index )
		return "Invalid error";
	return Error[ index ];
}

void ShowError()
{
	LPVOID lpMsgBuf;
	string message;
	DWORD error_code = GetLastError();
	do
	{
		message = ( char )( error_code % 10 + '0' ) + message;
		error_code /= 10;
	} while( error_code != 0 );
	if( !FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error_code, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), ( LPTSTR )&lpMsgBuf, 0, NULL ) )
	   return;
	message = "Error #" + message + ": " + ( char * )lpMsgBuf;
	LocalFree( lpMsgBuf );
	MessageBox( NULL, ( LPCTSTR )message.c_str(), "Error", MB_OK | MB_ICONINFORMATION );
	Log.Error( message.c_str() );
}